<template>
  <div class="app-container">
    <!-- 策略列表 -->
    <div class="cqt-box-item">
        <h3>用户列表
            <el-button type="primary"  size="mini"  @click="handleAddUser()" >添加 <i class="el-icon-upload el-icon--right"></i></el-button>
        </h3>
        <el-table
            :data="userList"
            border
            stripe
            style="width:100%">
            <el-table-column
                prop="id"
                label="用户ID"
                align="center"
                width="180">
            </el-table-column>

            <el-table-column
                prop="name"
                label="用户名"
                align="center"
                width="180">
            </el-table-column>

            <el-table-column
                prop="password"
                label="用户密码"
                align="center"
                width="400">
            </el-table-column>

            <el-table-column
                prop="role"
                label="用户权限"
                align="center"
                width="400">
            </el-table-column>

            <el-table-column
                label="操作"
                align="center">
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button
                        size="mini"
                        type="danger"
                        @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>

        </el-table>

        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="requestData.currentPage"
            :page-sizes="[50, 100, 150, 200]"
            :page-size="requestData.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="logTotal">
        </el-pagination>
    </div>


     <!-- 用户信息编辑 -->
    <el-dialog title="用户信息编辑" :visible.sync="dialogUserFormVisible">
        <el-form :model="userForm">
            <el-form-item label="用户ID" label-width="120px">
                <el-input v-model="userForm.id" auto-complete="off" disabled></el-input>
            </el-form-item>

            <el-form-item label="用户名" label-width="120px">
                <el-input v-model="userForm.name" auto-complete="off" @change="editCheckName" ></el-input>
            </el-form-item>

            <el-form-item label="用户密码" label-width="120px">
                <el-input v-model="userForm.password" auto-complete="off" @change="editCheckPassword" ></el-input>
            </el-form-item>

              <el-form-item label="用户初始权限" label-width="120px">
              <el-checkbox-group 
                  :min="0"
                  :max="1"
                  v-model="EditUserRole">
                  <el-checkbox v-for="city in cities" :label="city.key" :key="city.key" >{{city.value}}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
           
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogUserFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitUserEdit">确 定</el-button>
        </div>
    </el-dialog>

      <!-- 用户信息新增 -->
    <el-dialog title="用户信息新增 " :visible.sync="dialogAddUserFromVisible">

        <el-form :model="nullObject">
            <el-form-item label="用户名称" label-width="120px">
                <el-input v-model="AddUserForm.name" auto-complete="off" @change="checkName"></el-input>
            </el-form-item>
           
           <el-form-item label="用户密码" label-width="120px">
                <el-input v-model="AddUserForm.password" auto-complete="off" @change="checkPassword" ></el-input>
            </el-form-item>


            <el-form-item label="用户初始权限" label-width="120px">
              <el-checkbox-group 
                  :min="0"
                  :max="1"
                  v-model="AddUserRole">
                  <el-checkbox v-for="city in cities" :label="city.key" :key="city.key" >{{city.value}}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
           

        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogAddUserFromVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitUserAdd">确 定</el-button>
        </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getUserList,
  deleteUser,
  addUser,
  updateUser,
  hasUserByName
} from "@/api/user";
const cityOptions = [
  { key: "root", value: "可创建策略" },
  { key: "editor", value: "仅可查看策略" }
];
export default {
  data() {
    return {
      EditUserRole: [],
      AddUserRole: [],
      cities: cityOptions,
      nullArray: [],
      nullObject: null,
      nullString: null,

      dialogUserFormVisible: false,
      dialogAddUserFromVisible: false,

      AddUserForm: {
        name: null,
        password: null
      },

      userForm: {
        id: null,
        name: null,
        password: null
      },
      userList: [],

      logTotal: 0,
      requestData: {
        currentPage: 1,
        pageSize: 50
      },

      //缓存一份编辑前的用户名
      editBeforeData: null
    };
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      // 初始化请求
      this.loadUserList();
    },

    //加载所有的用户列表
    loadUserList() {
      getUserList(this.requestData).then(response => {
        var data = response.data;
        this.userList = data.list;
        this.logTotal = data.total;
      });
    },

    //用户信息编辑编辑页面（处理器）
    handleEdit(index, row) {
      this.userForm = {
        id: row.id,
        name: row.name,
        password: row.password
      };

      this.editBeforeData = row.name;

      this.EditUserRole = [row.role];
      this.dialogUserFormVisible = true;
    },

    //编辑用户信息完成之后确认更新
    submitUserEdit() {
      var data = {
        id: this.userForm.id,
        name: this.userForm.name,
        password: this.userForm.password,
        role: this.EditUserRole.join(",")
      };

      //校验用户名
      if (this.userForm.name == "" || this.userForm.name == null) {
        alert("用户名不能为空！");
        this.userForm.name == "";
        return;
      }

      //校验用户密码
      if (this.userForm.password == "" || this.userForm.password == null) {
        alert("密码不能为空！");
        this.userForm.password == "";
        return;
      }

      //判断用户名是否发生变化
      if (this.userForm.name != this.editBeforeData) {
        //如果发生变化判断用户名是否重复
        var params = {
          name: this.userForm.name
        };

        hasUserByName(params).then(response => {
          if (response.data) {
            alert("用户名已被占用，请您重新命名");
            this.userForm.name = "";
            return;
          }

          //如果不存在则进行更行
          // TODO 验证是否重复-->进行修改或者新增
          updateUser(data)
            .then(response => {
              this.$message("操作成功!");
              this.dialogUserFormVisible = false;
              this.loadUserList();
              //缓存数据清零
              this.userForm = {
                id: null,
                name: null,
                password: null
              };

              this.EditUserRole = [];
            })
            .catch(err => {
              console.log(response.msg);
            });
        });
      } else {
        // TODO 验证是否重复-->进行修改或者新增
        updateUser(data)
          .then(response => {
            this.$message("操作成功!");
            this.dialogUserFormVisible = false;
            this.loadUserList();
            //缓存数据清零
            this.userForm = {
              id: null,
              name: null,
              password: null
            };

            this.EditUserRole = [];
          })
          .catch(err => {
            console.log(response.msg);
          });
      }
    },

    //新增用户页面
    handleAddUser() {
      this.dialogAddUserFromVisible = true;
    },

    //提交用户的新增信息
    submitUserAdd() {
      var data = {
        id: null,
        name: this.AddUserForm.name,
        password: this.AddUserForm.password,
        role: this.AddUserRole.join(",")
      };

      const reg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{8,16}$/;
      if (this.AddUserForm.name == "" || this.AddUserForm.name == null) {
        alert("用户名不能为空！");
        return;
      }
      if (!reg.test(this.AddUserForm.password)) {
        alert("密码不能小于8位！必须包含大小写字母和数字");
        this.AddUserForm.password = "";
        return;
      }

      //判断用户名是否重复
      var params = {
        name: this.AddUserForm.name
      };

      hasUserByName(params).then(response => {
        if (response.data) {
          alert("用户名已被占用，请您重新命名");
          this.AddUserForm.name = "";
          return;
        }
      });

      addUser(data).then(response => {
        this.$message("操作成功!");
        this.dialogAddUserFromVisible = false;
        this.loadUserList();

        this.AddUserForm = {
          name: null,
          password: null
        };
        this.AddUserRole = [];
      }).catch(err => {
            console.log(response.msg);
          });
    },

    //删除某条用户信息
    handleDelete(index, row) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          //准备参数
          //先将该参数删除之后将所有配置信息重新提交
          this.userList.splice(index, 1);
          // TODO 发出删除请求
          var params = {
            id: row.id
          };
          deleteUser(params).then(response => {
            this.$message({
              type: "success",
              message: "删除成功!"
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },

    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.requestData.pageSize = val;
      this.loadUserList();
    },

    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.requestData.currentPage = val;
      this.loadUserList();
    },

    /**
     * 校验用户密码
     */
    checkPassword(val) {
      const reg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{8,16}$/;
      if (!reg.test(val)) {
        alert("密码不能小于8位！必须包含大小写字母和数字");
        this.AddUserForm.password = "";
        return;
      }
    },

    /**
     * 校验用户名是否为空或者是否已经存在
     */

    checkName(val) {
      if (this.AddUserForm.name == "" || this.AddUserForm.name == null) {
        alert("用户名不能为空！");
        this.AddUserForm.name == "";
        return;
      }

      //判断用户名是否重复
      var params = {
        name: this.AddUserForm.name
      };

      hasUserByName(params).then(response => {
        if (response.data) {
          alert("用户名已被占用，请您重新命名");
          this.AddUserForm.name = "";
          return;
        }
      });
    },

    /**
     * 编辑用户信息时校验用户密码
     */
    editCheckPassword(val) {
      if (val == null || val == "") {
        alert("密码不能为空");
        this.password = "";
        return;
      }
    },

    /**
     * 校验编辑用户信息时
     */
    editCheckName(val) {
      if (val == "" || val == null) {
        alert("用户名不能为空！");
        this.userForm.name == "";
        return;
      }

      //判断用户名是否发生变化
      if (this.userForm.name != val) {
        //如果发生变化判断用户名是否重复
        var params = {
          name: this.userForm.name
        };

        hasUserByName(params).then(response => {
          if (response.data) {
            alert("用户名已被占用，请您重新命名");
            this.userForm.name = "";
            return;
          }
        }).catch(err => {
            console.log(response.msg);
          });;
      }
    }
  }
};
</script>

<style scoped>
.cell .el-tag {
  margin-left: 2px;
  margin-right: 2px;
}
.el-table {
  margin-bottom: 20px;
}
.cqt-caption {
  font-size: 14px;
  color: #ccc;
  padding: 10px 20px;
  background-color: #f7f7f7;
  border-radius: 4px;
  margin: 0;
}
</style>
